package com.jinzhu.config;


import com.alibaba.fastjson.JSONObject;
import com.jinzhu.wrapper.XssHttpServletRequestWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 基于Filter的跨域  做sql xss 攻击
 */
@WebFilter
//@Configuration
@Component
public class CrosXssFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(CrosXssFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //跨域设置
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("application/json; charset=utf-8");
        if(response instanceof HttpServletResponse){
            HttpServletResponse httpServletResponse=(HttpServletResponse)response;
            //通过在响应 header 中设置 ‘*’ 来允许来自所有域的跨域请求访问。
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
            //通过对 Credentials 参数的设置，就可以保持跨域 Ajax 时的 Cookie
            //设置了Allow-Credentials，Allow-Origin就不能为*,需要指明具体的url域
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            //请求方式
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "*");
            //（预检请求）的返回结果（即 Access-Control-Allow-Methods 和Access-Control-Allow-Headers 提供的信息） 可以被缓存多久
            httpServletResponse.setHeader("Access-Control-Max-Age", "86400");
            //首部字段用于预检请求的响应。其指明了实际请求中允许携带的首部字段   跨域错误主要在这里 如果出现跨域是否在这里找不到前端请求头
            httpServletResponse.setHeader("Access-Control-Allow-Headers", "POST,GET,OPTIONS,DELETE,PUT,HEAD," +
                    "token,Origin,X-Requested-With, " +
                    "Content-Type,Accept," +
                    "headerUserId,headerUserToken");
        }
        //sql,xss过滤
        HttpServletRequest httpServletRequest=(HttpServletRequest)request;
        logger.info("CrosXssFilter.......orignal url:{},ParameterMap:{}",httpServletRequest.getRequestURI(), JSONObject.toJSONString(httpServletRequest.getParameterMap()));
        XssHttpServletRequestWrapper xssHttpServletRequestWrapper=new XssHttpServletRequestWrapper(
                httpServletRequest);
        chain.doFilter(xssHttpServletRequestWrapper, response);
        logger.info("CrosXssFilter..........doFilter url:{},ParameterMap:{}",xssHttpServletRequestWrapper.getRequestURI(), JSONObject.toJSONString(xssHttpServletRequestWrapper.getParameterMap()));

    }

    @Override
    public void destroy() {

    }
//    @Bean
//    public CorsFilter corsFilter() {
//        // 1. 添加cors配置信息
//        CorsConfiguration config = new CorsConfiguration();
//        config.addAllowedOrigin("http://172.18.1.219:8080");
//        config.addAllowedOrigin("http://shop.z.mukewang.com:8080");
//        config.addAllowedOrigin("http://center.z.mukewang.com:8080");
//        config.addAllowedOrigin("http://shop.z.mukewang.com");
//        config.addAllowedOrigin("http://center.z.mukewang.com");
//        config.addAllowedOrigin("*");
//
//        // 设置是否发送cookie信息
//        config.setAllowCredentials(true);
//
//        // 设置允许请求的方式
//        config.addAllowedMethod("*");
//
//        // 设置允许的header
//        config.addAllowedHeader("*");
//
//        // 2. 为url添加映射路径
//        UrlBasedCorsConfigurationSource corsSource = new UrlBasedCorsConfigurationSource();
//        corsSource.registerCorsConfiguration("/**", config);
//
//        // 3. 返回重新定义好的corsSource
//        return new CorsFilter(corsSource);
//    }
//    public CrosXssFilter() {}
}
